import { useState, useEffect, useRef } from 'react'
import './index.less';
import { Button, Card, Checkbox, Switch } from 'antd';
import useMap from '../../hooks/useMap';
import DataDetail from '../DataDetail';
import DragDiv from '../../../../../../framework/DragDiv';
import { resourcePath } from '../../../../../../../utils/resource';

let lastPos = {
    left: 480,
    bottom: 20
}
export default function Legend(props) {
    const map = useMap();
    const [layerItems, setLayerItems] = useState([]);
    const layerRef = useRef();
    const [baseLayerItems, setBaseLayerItems] = useState([]);

    useEffect(() => {
        const handler = evt => {
            console.log(evt)
            setLayerItems(items => {
                layerRef.current = [...items, evt];
                return [...items, evt]
            });
        }
        map.on('legend-layer', handler)
        return () => {
            map.un('legend-layer', handler);
        }
    }, [map])

    // useEffect(() => {
    //     const handler = evt => {
    //         setBaseLayerItems(items => {
    //             evt.layer?.set('base-layer', 1);
    //             layerRef.current = [...items, evt];
    //             return [...items, evt]
    //         });
    //     }
    //     map.on('legend-base-layer', handler)
    //     return () => {
    //         map.un('legend-base-layer', handler);
    //     }
    // }, [])

    useEffect(() => {
        return () => {
            layerRef.current?.forEach(item => {
                map.removeLayer(item.layer)
            })
        }
    }, [map])

    return <DragDiv className="legend" style={{
        ...lastPos
    }} onMoveEnd={e => {
        lastPos = e;
    }}>
        <div style={{
            background: `url(${resourcePath.legendBg})`,
            backgroundSize: '100% 100%',
            padding: "24px 16px"
        }}>
            <div className='layout-v j-center'>
                {layerItems.map(item => {
                    return <div className='layout-h center' key={item.title} style={{
                        marginBottom: 10
                    }}>
                        <img style={{
                            height: 30,
                            width: 'auto',
                            marginRight: 10
                        }} alt={item.title} src={item.icon} />
                        <div style={{
                            marginRight: 16
                        }}>{item.title}</div>
                        <Switch checked={item.layer.get('visible')} onChange={checked => {
                            item.layer.set('visible', checked);
                            setLayerItems(items => {
                                return [...items];
                            })
                        }} />
                    </div>
                })}
            </div>
            {props.extra}
        </div>
    </DragDiv>;
}